package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.collect.Lists;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.List;
import java.util.UUID;

/**
 * 咪咕http通道
 */
public class SmsApiMIGUv6 extends GateWayHttpAbstract
{

    public SmsApiMIGUv6(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    /**
     *
     * @param mt 下发的用户手机号码，多个号以英文逗号分隔，请求号码长度不超过50000个
     * @return
     */
    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
//        String t = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Document document = DocumentHelper.createDocument();
        Element requestElement = document.addElement("Request");
        //username
        Element userNameElement = requestElement.addElement("username");
        userNameElement.setText(paramsMaps.get("username"));

        //pwd
        Element pwdElement = requestElement.addElement("pwd");
        pwdElement.setText(paramsMaps.get("pwd"));

        //sendPort
        Element sendPortElement = requestElement.addElement("sendPort");
        sendPortElement.setText(paramsMaps.get("sendPort"));

        //to,50000个
        Element toElement = requestElement.addElement("to");
        toElement.setText(mt.getPhone());
        //msgContent
        Element msgContentElement = requestElement.addElement("msgContent");
        msgContentElement.setText(SignHelper.getContent(mt.getSmsContent()));

        //label
        Element labelElement = requestElement.addElement("label");
        labelElement.setText(SignHelper.get(mt.getSmsContent()));

        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/spi/sendSMS", document.getRootElement().asXML(), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, document.getRootElement().asXML(), result);

        List<SMSSRMessage> resultList = Lists.newArrayList();
        SMSSRMessage message = initGatewayResultMessage(result, mt, "resultCode");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        Document doucResult;
        try {
            doucResult = DocumentHelper.parseText(result);
            Element root = doucResult.getRootElement();
            if(StringUtils.equals(message.getResult(), "F10199")) {
                resultCode = root.element("resultCode").getStringValue();
                resultMessage = root.element("resultCode").getStringValue();
                if(StringUtils.equals(resultCode, "5000")) {
                    taskid = root.element("taskId").getStringValue();
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "5000");
                resultList.add(message);
            }
        }catch (DocumentException e) {
            e.printStackTrace();
            logger.info("提交网关结果解析错误，网关:{}, 请求:{}, 响应:{}", this.gateWayID, document.getRootElement().asXML(), result);
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                Element details = root.element("details");
                if (StringUtils.contains(text,"status")) {
                    logger.info("{}网关推送状态报告:{}", gateWayID, text);
                    List<Element> itemElements = details.elements("detail");
                    for (Element data : itemElements) {
                        SMSRTMessage smsRtMessage = initSmsRtMessage(data.element("taskId").getStringValue(), data.element("msisdn").getStringValue(),data.element("msisdn").getStringValue(),
                                data.element("status").getStringValue(), "1");
                        rtList.add(smsRtMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                Element details = root.element("details");
                if (StringUtils.contains(text,"msisdn")) {
                    logger.info("{}网关推送用户上行:{}", gateWayID, text);
                    List<Element> itemElements = details.elements("detail");
                    for (Element data : itemElements) {
                        SMSMOMessage sMSMOMessage = new SMSMOMessage();
                        sMSMOMessage.setGateWayID(gateWayID);
                        sMSMOMessage.setMsgContent(data.element("message").getStringValue());
                        sMSMOMessage.setPhone(data.element("msisdn").getStringValue());
                        sMSMOMessage.setSenttime(data.element("receivedTime").getStringValue());
                        sMSMOMessage.setSpnumber(data.element("address").getStringValue());
                        sMSMOMessage.setUuid(UUID.randomUUID().toString());
                        moList.add(sMSMOMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        return "无查询接口";
    }
    
    public static void main(String[] args)
    {
//        String params = "{\"username\":\"aaa\",\"pwd\":\"123456\",\"sendPort\":\"80\",\"apiUrl\":\"http://baidu.com\"}";
//        String params = "{\"userid\":\"258\",\"account\":\"hzfs-wd\",\"password\":\"hzfs-wd123\",\"apiUrl\":\"http://qxsmst.ronglaids.net\",\"extno\":\"\",\"statusNum\":\"4000\",\"deliverSecTime\":\"60\"}";
        String params = " {\"username\":\"hyzscmhz02\",\"pwd\":\"hzzj123\",\"sendPort\":\"9094\",\"apiUrl\":\"http://211.140.17.101:9094\"}";
        SmsApiMIGUv6 api = new SmsApiMIGUv6("ZY",params);
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18266846802");
        message.setId("test123456");
        message.setSmsContent("【等都科技】你的短信验证码是432446");
//        api.doSend(message);
//        api.queryDeliver("");
//        api.queryReport("");
//        String reportText = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><returnsms> <statusbox> <mobile>18268846802</mobile> <taskid>2082039</taskid> <status>10</status> <receivetime>2018-03-23 14:46:09</receivetime> <errorcode><![CDATA[DELIVRD]]></errorcode> <extno><![CDATA[2728]]></extno> </statusbox> </returnsms>";
        String a = "<Request>\n" +
                "  <details>\n" +
                "    <detail>\n" +
                "      <taskId>5b0e552490ee06cfbe5cd683</taskId>\n" +
                "      <msisdn>18268846802</msisdn>\n" +
                "      <status>0</status>\n" +
                "      <failedReason>etos:415</failedReason>\n" +
                "    </detail>\n" +
                "  </details>\n" +
                "</Request>";
//        api.parseReport(a, Lists.<SMSRTMessage>newArrayList());

        String b = "<Request>\n" +
                "  <details>\n" +
                "    <detail>\n" +
                "      <msisdn>18268846802</msisdn>\n" +
                "      <address>106580099510119094</address>\n" +
                "      <message>123</message>\n" +
                "      <receivedTime>20180530162456</receivedTime>\n" +
                "    </detail>\n" +
                "  </details>\n" +
                "  <username><![CDATA[hyzscmhz02]]></username>\n" +
                "  <pwd><![CDATA[hzzj123]]></pwd>\n" +
                "</Request>";

        api.parseDeliver(b,Lists.<SMSMOMessage>newArrayList());
    }
    
}